package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.bean.TradePaymentBean;
import com.atguigu.common.Constant;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.DorisUtil;
import com.atguigu.utils.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

//数据流:web/app -> Nginx -> 业务服务器(Mysql) -> Maxwell -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> Doris
//程  序:Mock -> Mysql -> Maxwell -> Kafka(ZK) -> Dwd04_TradeOrderDetail2 -> Kafka(ZK) -> Dwd06_TradePayDetailSuc -> Kafka(ZK) -> Dws08_TradePaymentSucWindow -> Doris
public class Dws08_TradePaymentSucWindow {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //1.1 开启CK
        env.enableCheckpointing(10000L);
        CheckpointConfig checkpointConfig = env.getCheckpointConfig();
        checkpointConfig.setCheckpointTimeout(20000L);
        checkpointConfig.setCheckpointStorage("hdfs://hadoop102:8020/flink-ck");
        checkpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        //checkpointConfig.setCheckpointInterval(10000L);
        checkpointConfig.setMinPauseBetweenCheckpoints(5000L);
        checkpointConfig.setMaxConcurrentCheckpoints(2);
        //默认是int类型的最大值
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5000L));
        env.setStateBackend(new HashMapStateBackend());

        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //2.读取Kafka DWD层加购主题数据
        DataStreamSource<String> kafkaDS = env.fromSource(
                KafkaUtil.getKafkaSource(Constant.TOPIC_DWD_TRADE_PAY_DETAIL_SUC, "dws_pay_detail_230315"),
                WatermarkStrategy.noWatermarks(),
                "kafka-source");

        //3.过滤&转换为JSON对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (!"".equals(value)) {
                    JSONObject jsonObject = JSON.parseObject(value);
                    out.collect(jsonObject);
                }
            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("callback_time");
            }
        }));

        //4.按照user_id进行分组  去重  转换为JavaBean对象
        KeyedStream<JSONObject, String> keyedStream = jsonObjDS.keyBy(json -> json.getString("user_id"));
        SingleOutputStreamOperator<TradePaymentBean> tradePaymentBeanDS = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, TradePaymentBean>() {

            private ValueState<String> lastPayDtState;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastPayDtState = getRuntimeContext().getState(new ValueStateDescriptor<String>("last-pay", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradePaymentBean> out) throws Exception {

                //取出状态数据
                String lastDt = lastPayDtState.value();
                String curDt = value.getString("callback_time").split(" ")[0];

                long payUserCt = 0L;
                long payNewUserCt = 0L;

                if (lastDt == null) {
                    payUserCt = 1L;
                    payNewUserCt = 1L;
                    lastPayDtState.update(curDt);
                } else if (!lastDt.equals(curDt)) {
                    payUserCt = 1L;
                    lastPayDtState.update(curDt);
                }

                //输出数据
                if (payUserCt == 1L) {
                    out.collect(new TradePaymentBean("", "", curDt, payUserCt, payNewUserCt));
                }
            }
        });

        //5.开窗聚合
        SingleOutputStreamOperator<TradePaymentBean> resultDS = tradePaymentBeanDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradePaymentBean>() {
                    @Override
                    public TradePaymentBean reduce(TradePaymentBean value1, TradePaymentBean value2) throws Exception {
                        value1.setPaymentSucNewUserCt(value1.getPaymentSucNewUserCt() + value2.getPaymentSucNewUserCt());
                        value1.setPaymentSucUniqueUserCt(value1.getPaymentSucUniqueUserCt() + value2.getPaymentSucUniqueUserCt());
                        return value1;
                    }
                }, new AllWindowFunction<TradePaymentBean, TradePaymentBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TradePaymentBean> values, Collector<TradePaymentBean> out) throws Exception {
                        TradePaymentBean next = values.iterator().next();
                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        out.collect(next);
                    }
                });

        //6.将数据写出到Doris
        resultDS.print("resultDS>>>>>>>>");
        resultDS.map(bean -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;  // 转成json的时候, 属性名使用下划线
                    return JSON.toJSONString(bean, config);
                })
                .sinkTo(DorisUtil.getDorisSink("dws_trade_payment_suc_window"));

        //7.启动
        env.execute("Dws08_TradePaymentSucWindow");
    }

}
